//index.js
//获取应用实例
const common = require("../../public.js");

Page({
  data: {
    realName: '',
    cardNo: ''
  },
  onLoad(options) {
    const that = this
    if (options.backUrl) {
      that.setData({
        backUrl: decodeURIComponent(options.backUrl)
      })
    }
    wx.getStorage({
      key: 'user',
      success: function (res) {
        that.setData({
          userInfo: res.data.user,
          token: res.data.token,
          openid: res.data.openid,
        })
      },
      fail: function (res) {
        common.showToast('没有用户信息')
      }
    })
  },
  inputValue(e) {
  },
  sureSubmit() {
    if (common.isEmptyString(this.data.realName)) {
      common.showToast('请输入姓名')
      return
    }
    if (common.isEmptyString(this.data.icardNo)) {
      common.showToast('请输入身份证号')
      return
    }
    this.submit()
  },
  // 返回指定界面
  popPage() {
    const that = this
    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 2] // 返会上个界面
    if (that.data.backUrl) {
      common.loginFunc().then(res => {
        wx.redirectTo({
          url: that.data.backUrl,
        })
      })
    } else {
      if (prevPage) {
        prevPage.onLoad()
      }
      wx.navigateBack({ // 返会上个界面
        delta: 1
      })
    }
  },
  cancel() {
    this.popPage()
  },
  submit() {
    const that = this
    const tempJson = {
      realName: that.data.realName,
      cardNo: that.data.icardNo,
      userId: that.data.userInfo.id,
      token: that.data.token
    }
    common.post('/user/verify', tempJson, function (res) {
      if (res.status === 200) {
        wx.showToast({
          title: '认证成功',
          success: function () {
            common.loginFunc().then(res => {
              if (res) {
                that.popPage();
              }
            })
          }
        })
      } else {
        common.showRequestErrMsg(res)
      }
    })
  }
})